<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
    <title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
Welcome
<br />
<input id="text" type="text" />
<button onclick="send()">发送消息</button>
<hr />
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr />
<div id="message"></div>
</body>

<script type="text/javascript">

    // var sid = '4d21a3e0-31c6-4c95-8138-2c082149e467';
    var site = 0;

    var ws;                     //websocket实例
    var lockReconnect = false;  //避免重复连接
    var wsUrl = "ws://172.16.10.105:8081/exampleWS";

    function createWebSocket(url) {
        try {
            url = url + "?" + site;
            console.log(url)
            ws = new WebSocket(url);
            initEventHandle();
        } catch (e) {
            reconnect(url);
        }
    }

    function initEventHandle() {
        ws.onclose = function () {
            setMessageInnerHTML("WebSocket连接关闭, 将会重连");
            reconnect(wsUrl);
        };
        ws.onerror = function () {
            setMessageInnerHTML("WebSocket连接发生错误, 将会重连");
            reconnect(wsUrl);
        };
        ws.onopen = function () {
            //心跳检测重置
            heartCheck.reset().start();
            setMessageInnerHTML("WebSocket连接成功");
        };
        ws.onmessage = function (event) {
            //如果获取到消息，心跳检测重置
            //拿到任何消息都说明当前连接是正常的
            heartCheck.reset().start();
            site = eval('(' + event.data + ')').site;
            setMessageInnerHTML(event.data);
        }
    }

    function reconnect(url) {
        if(lockReconnect) return;
        lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
            createWebSocket(url);
            lockReconnect = false;
        }, 2000);
    }


    // 心跳检测
    var heartCheck = {
        timeout: 5000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function(){
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
                ws.send("连接心跳......");
                self.serverTimeoutObj = setTimeout(function () {
                    ws.close();
                }, self.timeout)
            }, this.timeout)
        }
    }

    if ('WebSocket' in window) {
        createWebSocket(wsUrl);
    }
    else{
        alert('当前浏览器 Not support websocket');
    }

    // 发送消息
    function send() {
        var message = document.getElementById('text').value;
        ws.send(message);
    }

    // 关闭连接
    function closeWebSocket() {
        ws.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }
</script>
</html>

